// 移除外部相机包的导入
import 'dart:ui' as ui;
import 'package:camera/camera.dart';
import 'package:flutter/foundation.dart';
import 'package:camera_platform_interface/camera_platform_interface.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:screen/screen.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:path_provider/path_provider.dart';
import 'package:path/path.dart' as path;
import 'dart:async';
import 'dart:io';
import 'package:image_gallery_saver/image_gallery_saver.dart';
import 'l10n/app_localizations.dart';
import 'settings_page.dart';
import 'light_control_dialog.dart';
 import 'video_player_page.dart';
import 'dart:io' show Platform;
import 'package:flutter/foundation.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();

  // 请求权限
  await Permission.camera.request();
  await Permission.storage.request();

  SystemChrome.setPreferredOrientations([
    DeviceOrientation.portraitUp,
    DeviceOrientation.portraitDown,
  ]);
  SystemChrome.setEnabledSystemUIMode(SystemUiMode.immersiveSticky);

  // 加载保存的语言设置
  final prefs = await SharedPreferences.getInstance();
  final String languageCode = prefs.getString('language') ?? 'zh';

  runApp(MyApp(locale: Locale(languageCode)));
}

class MyApp extends StatefulWidget {
  final Locale? locale;

  const MyApp({super.key, this.locale});

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  Locale _locale = const Locale('zh');
  bool _isMirrorMode = false; // 控制相机预览是否镜像翻转

  // 相机控制相关变量
  List<CameraDescription> _cameras = [];
  CameraController? controller;
  CameraController? _cameraController;
  bool _isCameraInitialized = false;
  bool _isRearCameraSelected = true;
  bool _isRecordingVideo = false;
  XFile? _videoFile;
  DateTime? _recordingStartTime;

  @override
  void initState() {
    super.initState();
    _locale = widget.locale ?? const Locale('zh');
    _initCamera();
  }

  /// 初始化相机设备
  /// 1. 检查相机权限状态
  /// 2. 获取可用摄像头列表
  /// 3. 创建CameraController实例
  /// 4. 处理设备初始化异常
  Future<void> _initCamera() async {
    try {
      // 检查是否已授予相机权限
      if (!(await Permission.camera.isGranted)) {
        print('相机权限未授予');
        return;
      }

      // 获取设备摄像头列表
      _cameras = await CameraPlatform.instance.availableCameras();

      // 空设备检查
      if (_cameras.isEmpty) {
        print('没有可用的相机');
        setState(() => _isCameraInitialized = false);
        return;
      }

      // 安全释放旧控制器
      if (_cameraController != null) {
        await _cameraController!.dispose();
        _cameraController = null;
      }

      // 创建新的相机控制器
      // 安全获取相机索引
      final int cameraIndex =
          _isRearCameraSelected ? 0 : (_cameras.length > 1 ? 1 : 0);
      if (cameraIndex >= _cameras.length) {
        print('未找到对应摄像头索引: $cameraIndex, 可用相机数量: ${_cameras.length}');
        setState(() => _isCameraInitialized = false);
        return;
      }

      // 不需要额外的null检查，因为我们已经确保了索引有效
      final camera = _cameras[cameraIndex];

      _cameraController = CameraController(
        camera,
        ResolutionPreset.max,
        enableAudio: false,
        imageFormatGroup: ImageFormatGroup.jpeg,
      );

      // 添加监听器以便在控制器状态变化时更新UI
      _cameraController!.addListener(() {
        if (mounted) {
          setState(() {});
        }
      });

      // 异步初始化相机
      await _cameraController!.initialize();

      if (mounted) {
        setState(() => _isCameraInitialized = true);
      }
    } on CameraException catch (e) {
      // 处理相机异常
      print('相机异常: ${e.code}, ${e.description}');
      setState(() => _isCameraInitialized = false);
    } catch (e) {
      // 统一错误处理
      print('相机初始化错误: $e');
      if (mounted) {
        setState(() => _isCameraInitialized = false);
      }
    }
  }

  Future<void> _switchCamera() async {
    if (_cameras.length < 2 || !mounted) return;

    setState(() {
      _isRearCameraSelected = !_isRearCameraSelected;
      _isCameraInitialized = false;
    });

    try {
      if (_cameraController != null) {
        await _cameraController!.dispose();
      }

      // 安全获取相机索引
      final int cameraIndex =
          _isRearCameraSelected ? 0 : (_cameras.length > 1 ? 1 : 0);
      if (cameraIndex >= _cameras.length) {
        print('切换相机失败: 未找到对应摄像头索引: $cameraIndex, 可用相机数量: ${_cameras.length}');
        setState(() => _isCameraInitialized = false);
        return;
      }

      // 不需要额外的null检查，因为我们已经确保了索引有效
      final camera = _cameras[cameraIndex];

      _cameraController = CameraController(
        camera,
        ResolutionPreset.max,
        enableAudio: false,
      );

      // 异步初始化相机
      if (_cameraController != null) {
        try {
          await _cameraController!.initialize();
          if (mounted) {
            setState(() => _isCameraInitialized = true);
          }
        } catch (e) {
          print('相机初始化失败: $e');
          setState(() => _isCameraInitialized = false);
        }
      } else {
        print('相机控制器创建失败');
        setState(() => _isCameraInitialized = false);
      }
    } on CameraException catch (e) {
      print('切换相机异常: ${e.code}, ${e.description}');
      if (mounted) {
        setState(() {
          _isCameraInitialized = false;
        });
      }
    } catch (e) {
      print('切换相机错误: $e');
      if (mounted) {
        setState(() {
          _isCameraInitialized = false;
        });
      }
    }
  }

  /// 拍照并保存
  /// 保存到应用目录和相册
  Future<void> _takePhoto() async {
    // 添加对相机控制器的空值检查
    if (_cameraController == null || !_cameraController!.value.isInitialized) {
      print('相机未初始化，无法拍照');
      return;
    }

    try {
      // 拍摄照片
      final XFile photo = await _cameraController!.takePicture();

      // 保存到应用目录
      final directory = await getApplicationDocumentsDirectory();
      final String fileName = path.basename(photo.path);
      final String filePath = path.join(directory.path, fileName);
      await photo.saveTo(filePath);
      print('照片保存到应用目录成功: $filePath');

      // 保存到相册
      try {
        final result = await ImageGallerySaver.saveFile(filePath);
        final bool success = result['isSuccess'] ?? false;
        print('照片保存到相册结果: $success, 详情: $result');

        if (mounted) {
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(
              content: Text(success ? '照片已保存到相册' : '照片已保存到应用目录'),
              duration: const Duration(seconds: 2),
            ),
          );
        }
      } catch (e) {
        print('保存照片到相册失败: $e');
        if (mounted) {
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(content: Text('照片已保存到应用，但未能保存到相册: $e')),
          );
        }
      }
    } catch (e) {
      print('拍照错误: $e');
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('拍照失败: $e')),
        );
      }
    }
  }

  /// 录制视频
  Future<void> _recordVideo() async {
    // 空值检查
    if (_cameraController == null || !_cameraController!.value.isInitialized) {
      print('相机未初始化，无法录制视频');
      return;
    }

    if (_cameraController!.value.isInitialized) {
      print('相机已完成初始化，可以开始录制视频');
    } else {
      print('相机未完成初始化，无法录制视频');
      return;
    }

    if (_cameraController!.value.isRecordingVideo) {
      print('已经在录制视频中');
      return;
    }

    try {
      // 开始录制视频
      await _cameraController!.startVideoRecording();
      // 更改状态并开始计时
      setState(() {
        _isRecordingVideo = true;
        _recordingStartTime = DateTime.now();
      });
    } catch (e) {
      print('开始录制视频错误: $e');
    }
  }

  @override
  void dispose() {
    // 确保相机和其他资源正确释放
    _cameraController?.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: '坚果补光灯',
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
        useMaterial3: true,
      ),
      locale: _locale,
      localizationsDelegates: AppLocalizations.localizationsDelegates,
      supportedLocales: AppLocalizations.supportedLocales,
      home: const SupplementaryLightApp(),
    );
  }
}

class SupplementaryLightApp extends StatefulWidget {
  const SupplementaryLightApp({super.key});

  @override
  State<SupplementaryLightApp> createState() => _SupplementaryLightAppState();
}

class _SupplementaryLightAppState extends State<SupplementaryLightApp>
    with SingleTickerProviderStateMixin, WidgetsBindingObserver {
  // 当前选中的模式：预设颜色或色轮
  bool _isPresetMode = true;

  // 当前选中的颜色 - 修改默认值为小鸡黄
  Color _currentColor = const Color(0xFFFFEB3B); // 默认小鸡黄而不是白色

  // 灯光亮度和屏幕亮度
  double _lightBrightness = 1.0;
  double _screenBrightness = 1.0;

  // 相机控制器
  CameraController? _cameraController;
  List<CameraDescription> _cameras = [];
  bool _isCameraInitialized = false;
  bool _isRearCameraSelected = true;
  bool _isMirrorMode = false; // 确保此变量存在
  bool _isRecordingVideo = false; // 添加视频录制状态变量
  bool _isRecordingPaused = false; // 添加视频暂停状态变量
  XFile? _videoFile; // 添加视频文件变量

  // 倒计时相关变量
  Timer? _countdownTimer;
  int _countdownSeconds = 0;

  // 录制时长相关变量
  Timer? _recordingTimer;
  Duration _recordingDuration = Duration.zero;
  String _formattedDuration = '00:00';

  // 屏幕亮度控制器 - 使用Screen包

  // 用户自定义预设列表
  List<PresetColor> _userPresets = [];

  // 预设颜色列表
  late List<PresetColor> _presetColors;

  @override
  void initState() {
    super.initState();
    // 添加应用生命周期观察者
    WidgetsBinding.instance.addObserver(this);
    _loadUserPresets();
    _initScreenBrightness();
    _initCamera();

    // 初始化预设颜色列表
    _presetColors = [
      PresetColor('磨皮感', const Color(0xFF9C27B0)),
      PresetColor('冷白皮', const Color(0xFF80DEEA)),
      PresetColor('少女感', const Color(0xFFF8BBD0)),
      PresetColor('百搭光', Colors.white),
      PresetColor('小鸡黄', const Color(0xFFFFEB3B)),
      PresetColor('清新光', const Color(0xFF2196F3)),
      PresetColor('网感紫', const Color(0xFF673AB7)),
      PresetColor('落日灯', const Color(0xFFFF5722)),
    ];
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    // 处理应用生命周期变化
    if (_cameraController == null ||
        !(_cameraController?.value.isInitialized ?? false)) {
      return;
    }

    if (state == AppLifecycleState.inactive) {
      // 应用进入非活动状态，释放相机资源
      _cameraController?.dispose();
    } else if (state == AppLifecycleState.resumed) {
      // 应用恢复活动状态，重新初始化相机
      _initCamera();
    }
  }

  // 初始化屏幕亮度
  Future<void> _initScreenBrightness() async {
    try {
      // 在 OHOS 平台上，我们设置一个默认值
      _screenBrightness = 1.0;
      try {
        final brightness = await Screen.brightness;
        if (brightness != null) {
          _screenBrightness = brightness;
        }
      } catch (e) {
        debugPrint('Failed to get current brightness: $e');
      }
      setState(() {});
    } catch (e) {
      debugPrint('Failed to initialize screen brightness: $e');
    }
  }

  // 加载用户自定义预设 - 仅保留此方法用于初始化
  Future<void> _loadUserPresets() async {
    final prefs = await SharedPreferences.getInstance();
    final List<String>? presetStrings = prefs.getStringList('userPresets');

    if (presetStrings != null) {
      setState(() {
        _userPresets = presetStrings.map((presetString) {
          final parts = presetString.split('|');
          if (parts.length == 2) {
            final name = parts[0];
            final colorValue = int.parse(parts[1]);
            return PresetColor(name, Color(colorValue));
          }
          return PresetColor('未命名', Colors.white);
        }).toList();
      });
    }
  }

  // 预设颜色相关方法已移至LightControlDialog中

  // 显示底部控制面板
  void _showLightControlDialog() {
    LightControlDialog.show(
      context,
      initialColor: _currentColor,
      initialLightBrightness: _lightBrightness,
      initialScreenBrightness: _screenBrightness,
      onColorChanged: (color, lightBrightness, screenBrightness) {
        setState(() {
          _currentColor = color;
          _lightBrightness = lightBrightness;
          _screenBrightness = screenBrightness;
        });
      },
    );
  }

  /// 初始化相机设备
  /// 1. 检查相机权限状态
  /// 2. 获取可用摄像头列表
  /// 3. 创建CameraController实例
  /// 4. 处理设备初始化异常
  Future<void> _initCamera() async {
    try {
      // 检查是否已授予相机权限
      if (!(await Permission.camera.isGranted)) {
        print('相机权限未授予');
        return;
      }

      // 获取设备摄像头列表
      _cameras = await CameraPlatform.instance.availableCameras();

      // 空设备检查
      if (_cameras.isEmpty) {
        print('没有可用的相机');
        setState(() => _isCameraInitialized = false);
        return;
      }

      // 安全释放旧控制器
      if (_cameraController != null) {
        await _cameraController!.dispose();
        _cameraController = null;
      }

      // 创建新的相机控制器
      // 安全获取相机索引
      final int cameraIndex =
          _isRearCameraSelected ? 0 : (_cameras.length > 1 ? 1 : 0);
      if (cameraIndex >= _cameras.length) {
        print('未找到对应摄像头索引: $cameraIndex, 可用相机数量: ${_cameras.length}');
        setState(() => _isCameraInitialized = false);
        return;
      }

      // 不需要额外的null检查，因为我们已经确保了索引有效
      final camera = _cameras[cameraIndex];

      _cameraController = CameraController(
        camera,
        ResolutionPreset.max,
        enableAudio: false,
        imageFormatGroup: ImageFormatGroup.jpeg,
      );

      // 添加监听器以便在控制器状态变化时更新UI
      _cameraController!.addListener(() {
        if (mounted) setState(() {});
      });

      // 异步初始化相机
      await _cameraController!.initialize();

      if (mounted) {
        setState(() => _isCameraInitialized = true);
      }
    } on CameraException catch (e) {
      // 处理相机异常
      print('相机异常: ${e.code}, ${e.description}');
      setState(() => _isCameraInitialized = false);
    } catch (e) {
      // 统一错误处理
      print('相机初始化错误: $e');
      if (mounted) {
        setState(() => _isCameraInitialized = false);
      }
    }
  }

  Future<void> _switchCamera() async {
    if (_cameras.length < 2 || !mounted) {
      print('无法切换相机：相机数量不足或组件已卸载');
      return;
    }

    setState(() {
      _isRearCameraSelected = !_isRearCameraSelected;
      _isCameraInitialized = false;
    });

    try {
      // 安全释放旧控制器
      if (_cameraController != null) {
        if (_cameraController!.value.isInitialized) {
          await _cameraController!.dispose();
        }
        _cameraController = null;
      }

      // 安全获取相机索引
      final int cameraIndex =
          _isRearCameraSelected ? 0 : (_cameras.length > 1 ? 1 : 0);
      if (cameraIndex >= _cameras.length) {
        print('切换相机失败: 未找到对应摄像头索引: $cameraIndex, 可用相机数量: ${_cameras.length}');
        setState(() => _isCameraInitialized = false);
        return;
      }

      // 不需要额外的null检查，因为我们已经确保了索引有效
      final camera = _cameras[cameraIndex];

      _cameraController = CameraController(
        camera,
        ResolutionPreset.max,
        enableAudio: false,
        imageFormatGroup: ImageFormatGroup.jpeg,
      );

      // 添加监听器以便在控制器状态变化时更新UI
      _cameraController!.addListener(() {
        if (mounted) setState(() {});
      });

      // 异步初始化相机
      await _cameraController!.initialize();

      if (mounted) {
        setState(() => _isCameraInitialized = true);
        print('相机切换成功: ${camera.name}');
      }
    } on CameraException catch (e) {
      print('切换相机异常: ${e.code}, ${e.description}');
      if (mounted) {
        setState(() => _isCameraInitialized = false);
      }
    } catch (e) {
      print('切换相机错误: $e');
      if (mounted) {
        setState(() => _isCameraInitialized = false);
      }
    }
  }

  /// 拍照并保存到相册
  Future<void> _takePhoto() async {
    print("[拍照] 开始拍照并保存");
    // 检查相机初始化状态
    if (_cameraController == null || !_cameraController!.value.isInitialized) {
      print('[拍照] 相机未初始化，无法拍照');
      return;
    }

    try {
      // 拍摄照片
      print("[拍照] 正在拍摄...");
      final XFile photo = await _cameraController!.takePicture();
      print("[拍照] 拍摄成功: ${photo.path}");

      // 保存到应用目录
      final directory = await getApplicationDocumentsDirectory();
      final String fileName = path.basename(photo.path);
      final String filePath = path.join(directory.path, fileName);
      await photo.saveTo(filePath);
      print('[拍照] 照片保存到应用目录成功: $filePath');

      // 保存到相册
      try {
        print("[拍照] 开始保存到相册...");

        // ui.Image image = await filePath.toImage();
        final Uint8List imageBytes = await photo.readAsBytes();
        final ui.Image rawImage = await decodeImageFromList(imageBytes);
        print("[本地图像] 转换为 Image 对象成功");

        ByteData? byteData =
            await (rawImage.toByteData(format: ui.ImageByteFormat.png));
        print("[本地图像] 获取 ByteData 成功，大小: ${byteData?.lengthInBytes ?? 0} 字节");

        if (byteData != null) {
          print("[本地图像] 准备调用 ImageGallerySaver.saveImage");
          final result =
              await ImageGallerySaver.saveImage(byteData.buffer.asUint8List());
          print("[本地图像] 保存结果: $result");
        } else {
          print("[本地图像] 错误: ByteData 为空");
        }

        // 根据平台选择合适的保存方法
        final result = await ImageGallerySaver.saveFile(filePath);
        final bool success = result['isSuccess'] ?? false;
        print("[拍照] 保存到相册结果: $success, 详情: $result");
        print("[本地图像] 原生保存结果: $result");
        if (!success) {
          // 备用方案：保存字节数据
          await ImageGallerySaver.saveImage(byteData!.buffer.asUint8List());

          print("[本地图像] 原生字节数据: $result");
        }
        if (mounted) {
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(
              content: Text(success ? '照片已保存到相册' : '照片已保存到应用目录'),
              duration: const Duration(seconds: 2),
            ),
          );
        }
      } catch (e) {
        print('[拍照] 保存照片到相册失败: $e');
        if (mounted) {
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(content: Text('照片已保存到应用，但未能保存到相册: $e')),
          );
        }
      }
    } catch (e) {
      print('[拍照] 拍照错误: $e');
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('拍照失败: $e')),
        );
      }
    }
  }

  // Future<void> _takePhoto() async {
  //   // 添加对相机控制器的空值检查
  //   if (_cameraController == null || !_cameraController!.value.isInitialized) {
  //     print('相机未初始化，无法拍照');
  //     return;
  //   }

  //   // 检查是否正在拍照，避免重复操作
  //   if (_cameraController!.value.isTakingPicture) {
  //     print('正在拍照中，请稍候');
  //     return;
  //   }

  //   try {
  //     // 显示拍照反馈
  //     setState(() {});

  //     // 拍照并获取照片文件
  //     final XFile photo = await _cameraController!.takePicture();

  //     // 获取应用文档目录用于保存照片
  //     final directory = await getApplicationDocumentsDirectory();
  //     final String fileName = path.basename(photo.path);
  //     final String filePath = path.join(directory.path, fileName);

  //     // 保存照片到应用目录
  //     await photo.saveTo(filePath);

  //     // 显示成功消息
  //     print('照片保存成功: $filePath');

  //     // 可以在这里添加拍照成功的UI反馈，比如显示一个Snackbar
  //     if (mounted) {
  //       ScaffoldMessenger.of(context)
  //           .showSnackBar(SnackBar(content: Text('照片已保存')));
  //     }
  //   } on CameraException catch (e) {
  //     print('相机拍照异常: ${e.code}, ${e.description}');
  //   } catch (e) {
  //     print('拍照错误: $e');
  //   }
  // }

  /// 开始视频录制
  /// 1. 检查相机控制器状态
  /// 2. 开始录制视频
  /// 3. 更新UI状态
  /// 4. 启动录制时长计时器
  Future<void> _startVideoRecording() async {
    if (_cameraController == null) {
      print('相机控制器未初始化，无法录制视频');
      return;
    }

    if (_cameraController!.value.isInitialized) {
      print('相机已完成初始化，可以开始录制视频');
    } else {
      print('相机未完成初始化，无法录制视频');
      return;
    }

    if (_cameraController!.value.isRecordingVideo) {
      print('已经在录制视频中');
      return;
    }

    try {
      print('开始录制视频...');
      // 开始录制视频
      await _cameraController!.startVideoRecording();

      // 重置并启动录制时长计时器
      _resetRecordingTimer();
      _startRecordingTimer();

      // 更新UI状态
      setState(() {
        _isRecordingVideo = true;
        _isRecordingPaused = false;
      });

      // 显示录制开始提示
      if (mounted) {
        ScaffoldMessenger.of(context)
            .showSnackBar(const SnackBar(content: Text('视频录制开始')));
      }
    } on CameraException catch (e) {
      print('视频录制异常: ${e.code}, ${e.description}');
      setState(() {
        _isRecordingVideo = false;
        _isRecordingPaused = false;
      });
      _stopRecordingTimer();
    } catch (e) {
      print('视频录制错误: $e');
      setState(() {
        _isRecordingVideo = false;
        _isRecordingPaused = false;
      });
      _stopRecordingTimer();
    }
  }

  /// 同步录制状态
  /// 确保UI状态与相机控制器状态一致
  void _syncRecordingState() {
    if (_cameraController == null || !_cameraController!.value.isInitialized) {
      setState(() {
        _isRecordingVideo = false;
        _isRecordingPaused = false;
      });
      return;
    }

    setState(() {
      _isRecordingVideo = _cameraController!.value.isRecordingVideo;
      _isRecordingPaused = _cameraController!.value.isRecordingPaused;
    });
  }

  /// 暂停视频录制
  /// 检查状态并暂停录制
  Future<void> _pauseVideoRecording() async {
    if (_cameraController == null || !_cameraController!.value.isInitialized) {
      print('相机未初始化，无法暂停录制');
      return;
    }

    try {
      if (!_cameraController!.value.isRecordingVideo) {
        print('没有正在进行的视频录制，无法暂停');
        return;
      }

      if (_isRecordingPaused) {
        print('录制已经处于暂停状态，不需要再次暂停');
        return;
      }

      print('暂停视频录制...');
      await _cameraController!.pauseVideoRecording();

      // 暂停计时器
      _pauseRecordingTimer();

      setState(() {
        _isRecordingPaused = true;
      });

      print('视频录制已暂停');
    } on CameraException catch (e) {
      print('暂停视频录制异常: ${e.code}, ${e.description}');
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('暂停录制失败: ${e.description}')),
        );
      }
    } catch (e) {
      print('暂停视频录制错误: $e');
    }
  }

  /// 恢复视频录制
  /// 检查状态并恢复录制
  Future<void> _resumeVideoRecording() async {
    if (_cameraController == null || !_cameraController!.value.isInitialized) {
      print('相机未初始化，无法恢复录制');
      return;
    }

    try {
      // 确保只有当前处于暂停状态时才尝试恢复
      if (!_isRecordingPaused) {
        print('录制未处于暂停状态，无法恢复');
        return;
      }

      print('恢复视频录制...');
      await _cameraController!.resumeVideoRecording();

      // 恢复计时器
      _resumeRecordingTimer();

      setState(() {
        _isRecordingPaused = false;
      });

      print('视频录制已恢复');
    } on CameraException catch (e) {
      print('恢复视频录制异常: ${e.code}, ${e.description}');

      // 如果收到特定错误，可能需要重置录制状态
      if (e.description?.contains("avRecorder state is not paused") ?? false) {
        print('重置录制暂停状态，因为录制器实际上并未处于暂停状态');
        setState(() {
          _isRecordingPaused = false;
        });
      }

      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('恢复录制失败: ${e.description}')),
        );
      }
    } catch (e) {
      print('恢复视频录制错误: $e');
      // 出现未知错误时，尝试重置状态
      setState(() {
        _isRecordingPaused = false;
      });
    }
  }

  /// 开始倒计时录制
  /// 1. 开始3秒倒计时
  /// 2. 倒计时结束后自动开始录制
  void _startCountdownRecording() {
    // 如果已经在录制，则不启动倒计时
    if (_isRecordingVideo) {
      print('已经在录制视频中，无法启动倒计时');
      return;
    }

    // 取消已有倒计时（如果存在）
    _cancelCountdown();

    // 设置初始倒计时为3秒
    setState(() {
      _countdownSeconds = 3;
    });

    // 显示倒计时开始提示
    if (mounted) {
      ScaffoldMessenger.of(context)
          .showSnackBar(const SnackBar(content: Text('倒计时录制开始')));
    }

    // 创建定时器，每秒更新倒计时
    _countdownTimer = Timer.periodic(const Duration(seconds: 1), (timer) {
      setState(() {
        if (_countdownSeconds > 0) {
          _countdownSeconds--;
          // 显示当前倒计时
          print('倒计时: $_countdownSeconds 秒');
        } else {
          // 倒计时结束，开始录制
          _cancelCountdown();
          _startVideoRecording();
        }
      });
    });
  }

  /// 取消倒计时
  void _cancelCountdown() {
    if (_countdownTimer != null) {
      _countdownTimer!.cancel();
      _countdownTimer = null;
      print('倒计时已取消');
    }

    setState(() {
      _countdownSeconds = 0;
    });
  }

  /// 停止录制时长计时器
  void _stopRecordingTimer() {
    if (_recordingTimer != null) {
      if (_recordingTimer!.isActive) {
        _recordingTimer!.cancel();
      }
      _recordingTimer = null;
      print('录制计时器已停止');
    }
  }

  /// 重置录制时长计时器
  void _resetRecordingTimer() {
    _stopRecordingTimer();
    setState(() {
      _recordingDuration = Duration.zero;
      _formattedDuration = '00:00';
    });
  }

  /// 启动录制时长计时器
  void _startRecordingTimer() {
    _recordingTimer = Timer.periodic(const Duration(seconds: 1), (timer) {
      if (!mounted) return;

      setState(() {
        _recordingDuration = _recordingDuration + const Duration(seconds: 1);
        _formattedDuration = _formatDuration(_recordingDuration);
      });
    });
  }

  /// 暂停录制时长计时器
  void _pauseRecordingTimer() {
    if (_recordingTimer != null && _recordingTimer!.isActive) {
      _recordingTimer!.cancel();
    }
  }

  /// 恢复录制时长计时器
  void _resumeRecordingTimer() {
    _startRecordingTimer();
  }

  /// 格式化时长为 MM:SS 格式
  String _formatDuration(Duration duration) {
    String twoDigits(int n) => n.toString().padLeft(2, '0');
    final minutes = twoDigits(duration.inMinutes.remainder(60));
    final seconds = twoDigits(duration.inSeconds.remainder(60));
    return "$minutes:$seconds";
  }

  /// 打开视频文件
  /// 使用视频播放器页面查看已录制的视频
  void _openVideo(String filePath) {
    // 检查文件是否存在
    final file = File(filePath);
    file.exists().then((exists) {
      if (!exists) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(content: Text('视频文件不存在或已被移除')),
        );
        return;
      }

      // 打开视频播放页面
      Navigator.push(
        context,
        MaterialPageRoute(
          builder: (context) => VideoPlayerPage(videoPath: filePath),
        ),
      );
    });
  }

  /// 停止视频录制
  /// 1. 检查相机控制器状态
  /// 2. 停止录制并获取视频文件
  /// 3. 保存视频到应用目录和相册
  /// 4. 更新UI状态
  Future<void> _stopVideoRecording() async {
    print('开始停止视频录制处理...');

    // 先取消倒计时和停止计时器，确保即使后续代码失败，UI也能正确恢复
    _cancelCountdown();
    _stopRecordingTimer();

    // 检查相机状态
    if (_cameraController == null || !_cameraController!.value.isInitialized) {
      print('相机未初始化，无法停止录制');
      setState(() {
        _isRecordingVideo = false;
        _isRecordingPaused = false;
      });
      return;
    }

    if (!_cameraController!.value.isRecordingVideo) {
      print('没有正在进行的视频录制');
      setState(() {
        _isRecordingVideo = false;
        _isRecordingPaused = false;
      });
      return;
    }

    XFile? videoFile;
    try {
      print('正在停止相机录制...');
      if (_cameraController == null ||
          !_cameraController!.value.isInitialized) {
        print('相机控制器未初始化，无法停止录制');
        return;
      }
      if (!_cameraController!.value.isRecordingVideo) {
        print('当前没有进行视频录制');
        return;
      }

      // 停止录制并获取视频文件
        await _cameraController!.stopVideoRecording().then((XFile? file){
          videoFile=  file;
          if (videoFile == null) {
            print('停止录制失败：未获取到视频文件');
            return;
          }
        });

      print('相机录制已停止，文件路径: ${videoFile?.path}');
      print('准备调用_saveVideoToGallery方法...');

      // 立即更新UI状态，不等待保存过程
      if (mounted) {
        setState(() {
          _videoFile = videoFile;
          _isRecordingVideo = false;
          _isRecordingPaused = false;
        });
      }
      print('UI状态已更新，准备延迟执行保存操作...');

      // 使用延迟执行确保UI状态已更新，相机已完全释放资源
      Future.delayed(const Duration(milliseconds: 500), () async {
        print('开始执行延迟保存操作...');
        await _saveVideoToGallery(videoFile!);
      });
    } on CameraException catch (e) {
      print('停止视频录制异常: ${e.code}, ${e.description}');
      setState(() {
        _isRecordingVideo = false;
        _isRecordingPaused = false;
      });

      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('录制失败: ${e.description}')),
        );
      }
    } catch (e) {
      print('停止视频录制错误: $e');
      setState(() {
        _isRecordingVideo = false;
        _isRecordingPaused = false;
      });

      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(content: Text('录制失败，请重试')),
        );
      }
    }
  }

  /// 保存视频到相册
  /// 专门处理视频保存逻辑，支持鸿蒙系统
  Future<void> _saveVideoToGallery(XFile videoFile) async {
    print('开始保存视频到相册流程...');
    try {
      // 打印文件状态信息
      final File originalFile = File(videoFile.path);
      final bool fileExists = await originalFile.exists();
      final int fileSize = fileExists ? await originalFile.length() : 0;
      print('原始视频文件状态: 存在=$fileExists, 大小=${fileSize}字节, 路径=${videoFile.path}');

      if (!fileExists || fileSize == 0) {
        print('警告: 原始视频文件不存在或为空');
        if (mounted) {
          ScaffoldMessenger.of(context).showSnackBar(
            const SnackBar(content: Text('录制的视频文件异常，无法保存')),
          );
        }
        return;
      }

      // 1. 尝试基于平台选择最佳保存策略
      print('尝试平台自适应保存...');
      bool success = await saveVideoBasedOnPlatform(videoFile);

      if (success) {
        _showSaveSuccessMessage(videoFile.path, '视频已保存到相册');
        return;
      }

      // 2. 如果平台特定方法失败，尝试复制到应用目录再保存
      print('尝试复制到应用目录后再保存...');
      try {
        final directory = await getApplicationDocumentsDirectory();
        final String timestamp =
            DateTime.now().millisecondsSinceEpoch.toString();
        final String fileName = 'video_$timestamp.mp4';
        final String filePath = path.join(directory.path, fileName);

        // 确保目录存在
        await Directory(directory.path).create(recursive: true);
        print('应用目录创建完成: ${directory.path}');

        // 复制视频文件
        await originalFile.copy(filePath);
        final bool copiedFileExists = await File(filePath).exists();
        final int copiedFileSize =
            copiedFileExists ? await File(filePath).length() : 0;
        print(
            '复制后文件状态: 存在=$copiedFileExists, 大小=${copiedFileSize}字节, 路径=$filePath');

        if (!copiedFileExists || copiedFileSize == 0) {
          throw Exception('复制后的文件不存在或为空');
        }

        // 尝试使用复制的文件再次基于平台保存
        success = await saveVideoBasedOnPlatform(videoFile, filePath);

        if (success) {
          _showSaveSuccessMessage(filePath, '视频已保存到相册');
        } else {
          // 即使没保存到相册，至少文件保存在应用目录中
          _showSaveSuccessMessage(filePath, '视频已保存到应用');
        }
      } catch (e) {
        print('复制并保存失败: $e');
        if (mounted) {
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(content: Text('视频保存失败: $e')),
          );
        }
      }
    } catch (e) {
      print('视频保存过程失败: $e');
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('无法保存视频: $e')),
        );
      }
    }
  }

  /// 显示保存成功消息
  void _showSaveSuccessMessage(String filePath, String message) {
    if (!mounted) return;

    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text('$message (时长: $_formattedDuration)'),
        duration: const Duration(seconds: 4),
        action: SnackBarAction(
          label: '查看',
          onPressed: () => _openVideo(filePath),
        ),
      ),
    );
  }

  @override
  void dispose() {
    // 确保相机和其他资源正确释放
    _cameraController?.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final localizations = AppLocalizations.of(context);

    return Scaffold(
      body: Stack(
        children: [
          // 背景颜色 - 使用当前颜色并应用亮度
          Container(
            color: _currentColor.withOpacity(_lightBrightness),
          ),

          // 相机预览区域 - 如果相机已初始化则显示预览
          if (_isCameraInitialized && _cameraController != null)
            Positioned(
              top: 60,
              left: 20,
              right: 20,
              child: Container(
                height: 300,
                child: ClipRRect(
                  borderRadius: BorderRadius.circular(15),
                  child: AspectRatio(
                    aspectRatio: _cameraController?.value.previewSize != null
                        ? _cameraController!.value.previewSize!.width /
                            _cameraController!.value.previewSize!.height
                        : 4 / 3, // 使用默认的纵横比作为回退
                    child: Transform(
                      transform: Matrix4.identity()
                        ..scale(_isMirrorMode ? -1.0 : 1.0, 1.0, 1.0),
                      alignment: Alignment.center,
                      child: _cameraController != null
                          ? CameraPreview(_cameraController!)
                          : Container(color: Colors.black),
                    ),
                  ),
                ),
              ),
            ),

          // 相机控制按钮 - 右侧
          Positioned(
            top: 120,
            right: 20,
            child: Column(
              children: [
                // 相机切换按钮
                Container(
                  width: 50,
                  height: 50,
                  margin: const EdgeInsets.only(bottom: 15),
                  decoration: BoxDecoration(
                    color: Colors.black.withOpacity(0.5),
                    shape: BoxShape.circle,
                  ),
                  child: IconButton(
                    icon: const Icon(Icons.camera_alt, color: Colors.white),
                    onPressed: _initCamera,
                  ),
                ),

                // 相机翻转按钮
                Container(
                  width: 50,
                  height: 50,
                  margin: const EdgeInsets.only(bottom: 15),
                  decoration: BoxDecoration(
                    color: Colors.black.withOpacity(0.5),
                    shape: BoxShape.circle,
                  ),
                  child: IconButton(
                    icon:
                        const Icon(Icons.flip_camera_ios, color: Colors.white),
                    onPressed: _switchCamera,
                  ),
                ),

                // 三脚架模式按钮
                Container(
                  width: 50,
                  height: 50,
                  decoration: BoxDecoration(
                    color: Colors.black.withOpacity(0.5),
                    shape: BoxShape.circle,
                  ),
                  child: IconButton(
                    icon: const Icon(Icons.camera_front, color: Colors.white),
                    onPressed: () {
                      setState(() {
                        _isMirrorMode = !_isMirrorMode;
                      });
                    },
                  ),
                ),

                // 录制时长显示 - 仅在录制时显示
                if (_isRecordingVideo)
                  Container(
                    padding:
                        const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
                    margin: const EdgeInsets.only(bottom: 10),
                    decoration: BoxDecoration(
                      color: Colors.red.withOpacity(0.7),
                      borderRadius: BorderRadius.circular(20),
                    ),
                    child: Row(
                      mainAxisSize: MainAxisSize.min,
                      children: [
                        const Icon(Icons.fiber_manual_record,
                            color: Colors.white, size: 16),
                        const SizedBox(width: 5),
                        Text(
                          _formattedDuration,
                          style: const TextStyle(
                            color: Colors.white,
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                      ],
                    ),
                  ),

                // 视频录制按钮
                Container(
                  width: 50,
                  height: 50,
                  decoration: BoxDecoration(
                    color: Colors.black.withOpacity(0.5),
                    shape: BoxShape.circle,
                  ),
                  child: IconButton(
                    icon: Icon(
                      _isRecordingVideo ? Icons.stop : Icons.videocam,
                      color: _isRecordingVideo ? Colors.red : Colors.white,
                    ),
                    onPressed: () {
                      if (!_isCameraInitialized) {
                        print('相机未初始化，无法操作视频录制');
                        return;
                      }

                      if (_isRecordingVideo) {
                        _stopVideoRecording();
                      } else {
                        _startVideoRecording();
                      }
                    },
                  ),
                ),

                // 暂停/恢复录制按钮 - 仅在录制时显示
                if (_isRecordingVideo)
                  Container(
                    width: 50,
                    height: 50,
                    margin: const EdgeInsets.only(top: 10),
                    decoration: BoxDecoration(
                      color: Colors.black.withOpacity(0.5),
                      shape: BoxShape.circle,
                    ),
                    child: IconButton(
                      icon: Icon(
                        _isRecordingPaused ? Icons.play_arrow : Icons.pause,
                        color: Colors.white,
                      ),
                      onPressed: _isRecordingPaused
                          ? _resumeVideoRecording
                          : _pauseVideoRecording,
                    ),
                  ),

                // 倒计时录制按钮 - 仅在未录制时显示
                if (!_isRecordingVideo && _countdownSeconds == 0)
                  Container(
                    width: 50,
                    height: 50,
                    margin: const EdgeInsets.only(top: 10),
                    decoration: BoxDecoration(
                      color: Colors.black.withOpacity(0.5),
                      shape: BoxShape.circle,
                    ),
                    child: IconButton(
                      icon: const Icon(
                        Icons.timer,
                        color: Colors.white,
                      ),
                      onPressed: _isCameraInitialized
                          ? _startCountdownRecording
                          : null,
                    ),
                  ),

                // 倒计时显示 - 仅在倒计时进行中显示
                if (_countdownSeconds > 0)
                  Container(
                    width: 50,
                    height: 50,
                    margin: const EdgeInsets.only(top: 10),
                    decoration: BoxDecoration(
                      color: Colors.red.withOpacity(0.7),
                      shape: BoxShape.circle,
                    ),
                    child: Center(
                      child: Text(
                        "$_countdownSeconds",
                        style: const TextStyle(
                          color: Colors.white,
                          fontSize: 24,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                    ),
                  ),
              ],
            ),
          ),

          // 底部相机控制按钮
          Positioned(
            left: 0,
            right: 0,
            bottom: 80,
            child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                // 拍照按钮
                GestureDetector(
                  onTap: _isCameraInitialized ? _takePhoto : null,
                  child: Container(
                    width: 80,
                    height: 80,
                    decoration: BoxDecoration(
                      color: _isCameraInitialized
                          ? Colors.white.withOpacity(0.3)
                          : Colors.grey.withOpacity(0.3),
                      shape: BoxShape.circle,
                      border: Border.all(
                          color:
                              _isCameraInitialized ? Colors.white : Colors.grey,
                          width: 3),
                    ),
                    child: Center(
                      child: Container(
                        width: 70,
                        height: 70,
                        decoration: const BoxDecoration(
                          color: Colors.white,
                          shape: BoxShape.circle,
                        ),
                      ),
                    ),
                  ),
                ),
              ],
            ),
          ),

          // 底部控制按钮
          Positioned(
            left: 0,
            right: 0,
            bottom: 20,
            child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                // 灯光控制按钮
                GestureDetector(
                  onTap: _showLightControlDialog,
                  child: Container(
                    padding: const EdgeInsets.symmetric(
                        horizontal: 20, vertical: 12),
                    decoration: BoxDecoration(
                      color: Colors.black87,
                      borderRadius: BorderRadius.circular(30),
                    ),
                    child: Row(
                      mainAxisSize: MainAxisSize.min,
                      children: [
                        const Icon(
                          Icons.lightbulb_outline,
                          color: Colors.white,
                        ),
                        const SizedBox(width: 8),
                        Text(
                          localizations.appTitle,
                          style: const TextStyle(
                            color: Colors.white,
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                      ],
                    ),
                  ),
                ),

                // 设置按钮
                Container(
                  margin: const EdgeInsets.only(left: 10),
                  decoration: BoxDecoration(
                    color: Colors.black87,
                    shape: BoxShape.circle,
                  ),
                  child: IconButton(
                    onPressed: () {
                      // 打开设置页面
                      Navigator.push(
                        context,
                        MaterialPageRoute(
                          builder: (context) => const SettingsPage(),
                        ),
                      );
                    },
                    icon: const Icon(
                      Icons.settings,
                      color: Colors.white,
                      size: 24,
                    ),
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  // 预设颜色相关方法已移至LightControlDialog中

  // 色轮选择器和亮度控制相关方法已移至LightControlDialog中
}

// 预设颜色模型
class PresetColor {
  final String name;
  final Color color;

  const PresetColor(this.name, this.color);
}

/// 检测当前平台是否是鸿蒙系统bool isHarmonyOS() {
bool isHarmonyOS() {
  return TargetPlatform == TargetPlatform.ohos;
}

/// 基于当前环境确定视频保存策略
Future<bool> saveVideoBasedOnPlatform(XFile videoFile,
    [String? outputPath]) async {
  print('根据平台选择视频保存策略...');
  print('视频文件信息: 路径=${videoFile.path}, 输出路径=${outputPath ?? "使用原始路径"}');

  try {
    if (isHarmonyOS()) {
      print('检测到鸿蒙系统，使用特殊保存方法');
      return await saveVideoForHarmonyOS(videoFile, outputPath);
    } else {
      print('使用标准保存方法');
      return await saveVideoStandard(videoFile, outputPath);
    }
  } catch (e) {
    print('视频保存策略选择错误: $e');
    print('尝试使用标准保存方法作为备选方案...');
    return await saveVideoStandard(videoFile, outputPath);
  }
}

/// 针对鸿蒙系统的视频保存
Future<bool> saveVideoForHarmonyOS(XFile videoFile,
    [String? outputPath]) async {
  print('执行鸿蒙系统特殊视频保存...');

  try {
    // 鸿蒙系统可能需要特定的文件操作流程
    final String fileToSave = outputPath ?? videoFile.path;
    print('准备保存的文件路径: $fileToSave');

    // 1. 确认文件权限
    final File file = File(fileToSave);
    final bool fileExists = await file.exists();
    final int fileSize = fileExists ? await file.length() : 0;
    print('文件状态检查: 存在=$fileExists, 大小=${fileSize}字节');

    if (!fileExists) {
      print('鸿蒙特殊保存: 文件不存在 $fileToSave');
      return false;
    }

    print('开始调用ImageGallerySaver.saveFile...');
    // 2. 使用特定参数调用保存API
    final result = await ImageGallerySaver.saveFile(
      fileToSave,
      isReturnPathOfIOS: false, // 鸿蒙系统不需要iOS特性
    );

    final bool success = result['isSuccess'] ?? false;
    print('鸿蒙保存结果: success=$success');
    print('保存返回详情: $result');
    return success;
  } catch (e) {
    print('鸿蒙特殊保存方法失败: $e');
    print('错误堆栈: ${e.toString()}');
    return false;
  }
}

/// 标准视频保存方法
Future<bool> saveVideoStandard(XFile videoFile, [String? outputPath]) async {
  print('执行标准视频保存...');

  try {
    final String fileToSave = outputPath ?? videoFile.path;

    // 标准保存方法
    final result = await ImageGallerySaver.saveFile(fileToSave);
    final bool success = result['isSuccess'] ?? false;
    print('标准保存结果: $success, 详情: $result');
    return success;
  } catch (e) {
    print('标准保存方法失败: $e');
    return false;
  }
}
